package cn.flying.cloud.flow.core.configuration;

import javax.annotation.Resource;

import org.flowable.common.engine.impl.cfg.IdGenerator;
import org.flowable.engine.RuntimeService;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.flow.core.listener.event.GlobalEventListenerHandler;

/**
 * flowable配置
 *
 * @author: admin
 * @date: 2024年09月18日 10:42
 * @version: 1.0
 */
@Configuration
@Component
public class FlowableConfiguration implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration>, ApplicationRunner {

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private GlobalEventListenerHandler globalEventListenerHandler;

    /**
     * 为放置生成的流程图中中文乱码
     *
     * @param configuration
     */
    @Override
    public void configure(SpringProcessEngineConfiguration configuration) {
        configuration.setActivityFontName("宋体");
        configuration.setLabelFontName("宋体");
        configuration.setAnnotationFontName("宋体");
        // true 开启异步定时器，流程中节点需要采用异步执行，因为如果同步的情况，那么整个流程的事务处理是在一个事务中的，异常后会全部回滚，默认为true
        configuration.setAsyncExecutorActivate(true);

        // 添加自定义得Id生成器
        configuration.setIdGenerator(idGenerator());
    }

    private IdGenerator idGenerator() {
        return Ft.Snowflake::nextIdStr;
    }

    /**
     * 添加全局事件监听器
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 添加全局事件监听器
        runtimeService.addEventListener(globalEventListenerHandler);
    }
}